"""
    Authentication controller. Needs for readrds-2 authentication.
"""

from __future__ import with_statement
import threading
import random
import md5
import genshi
from string import letters
from turbogears import expose, controllers
from mnemoply import model

class AuthController(controllers.Controller):
    allow_anonymous = True
    preauth_session = []
    confirm_pass = "superpass"
    string_length = 32

    def __init__(self):
        controllers.Controller.__init__(self)
        self.lock = threading.Lock()

    def get_random_string(self):
        s = ''.join([random.choice(letters) for x in xrange(self.string_length)])
        self.preauth_session.append(s)
        return s

    @expose()
    def index(self, **kw):
        return self.get_random_string()

    @expose()
    def check(self, *arg, **kw):

        # return new hash
        def add_hash(hash1, hash2):
            return md5.new(hash1 + md5.new(hash2).hexdigest()).hexdigest()

        with self.lock:
            if self.preauth_session.count(kw['server_response']):
                self.preauth_session.remove(kw['server_response'])

                user = model.AuthUser.selectBy(user_name=arg[0])[0]
                check_string = add_hash(kw['server_response'], user.password)

                if check_string == kw['client_response']:
                    context = dict(
                        hash=add_hash(check_string, self.confirm_pass),
                        user=user,
                        groups=user.groups,
                    )

                    # render it
                    loader = genshi.template.loader.TemplateLoader(['.'])
                    template = loader.load('mnemoply/templates/auth.html')
                    return template.generate(**context).render()

        return "Authentication failed"

    @expose()
    def show_all(self, **kw):
        """
            Debug method.
        """

        return self.preauth_session

exposed = AuthController()
